package com.example.amqplistening.listener;

import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.time.LocalDateTime;

@Component
public class SpringRabbitListenerSimple {

//    @RabbitListener(queues = "simple.queue")
//    public void listening(String m){
//        System.out.println("消费者接收到信息"+m);
//    }

    @RabbitListener(queues = "simple.queue")
    public void listenWorkQueueMessage1(User msg, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag, Channel channel) throws InterruptedException {
        System.out.println("消费者1 接收到消息：【" + msg.toString() + "】" + LocalDateTime.now());
        try {
            channel.basicReject(deliveryTag, true); //如果没有其他队列，这里会一直收到信息
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        // 休眠20ms，1s大致能处理50条消息
    }

    //
    @RabbitListener(queues = "simple.queue")
    public void listenWorkQueueMessage2(User msg, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag, Channel channel) throws InterruptedException {
        System.err.println("消费者2........接收到消息：【" + msg.toString() + "】" + LocalDateTime.now());
        try {
            channel.basicAck(deliveryTag, false);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

//    @RabbitListener(queues = "queue1")
//    public void listenFanoutQueue1(String msg) {
//        System.out.println("消费者1收到广播消息：【" + msg + "】");
//    }
//
//    @RabbitListener(queues = "queue2")
//    public void listenFanoutQueue2(String msg) {
//        System.out.println("消费者2收到广播消息：【" + msg + "】");
//    }

//    @RabbitListener(
//            bindings = @QueueBinding(
//                    value = @Queue(name = "direct.quque1"),
//                    exchange = @Exchange(name = "directExchange", type = ExchangeTypes.DIRECT),
//                    key = {"all", "a"}
//            )
//    )
//    public void listenDirectQueue1(String msg) {
//        System.out.println("消费者1收到消息：【" + msg + "】");
//    }
//
//    @RabbitListener(
//            bindings = @QueueBinding(
//                    value = @Queue(name = "direct.quque2"),
//                    exchange = @Exchange(name = "directExchange", type = ExchangeTypes.DIRECT),
//                    key = {"all", "b"}
//            )
//    )
//    public void listenDirectQueue2(String msg) {
//        System.out.println("消费者2收到消息：【" + msg + "】");
//    }

}
